package edu.sctu.nieyu.day20150628exam.deal;

import com.alibaba.fastjson.JSONObject;
import edu.sctu.nieyu.day20150628exam.data.GoodsData;
import edu.sctu.nieyu.day20150628exam.deal.HttpUtil;

import java.io.*;

/**
 * Created by user01 on 2015/6/28.
 */

/**
 * Json解析类
 */
public class JsonUtil {
    /**
     * 将Json值传给data
     * @param jsonfile
     * @return
     * @throws IOException
     */
    public GoodsData jsonMessage(String jsonfile) throws IOException {
        File file = new File(jsonfile);
        FileInputStream fileInputStream = new FileInputStream(file);
        String message = HttpUtil.steamString(fileInputStream);
        GoodsData data = new GoodsData();
        data = JSONObject.parseObject(message, GoodsData.class);
        return data;
    }

    /**
     * 对data进行序列化到文件的操作
     * @param goodsData
     * @param filePath
     */
    public void SerializableJson(GoodsData goodsData, String filePath) {

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
            ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
            outputStream.writeObject(goodsData);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 对其进行反序列化操作，并读取
     * @param filePath
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public GoodsData antiSerializableJson(String filePath) throws IOException, ClassNotFoundException {

        FileInputStream fileInputStream = new FileInputStream(new File(filePath));
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        GoodsData goodsData = (GoodsData) objectInputStream.readObject();
        return goodsData;
    }

}
